package com.apes.fn.business.insurance.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.insurance.modle.*;
import com.apes.fn.business.insurance.repository.CommissionReconciliationRepository;
import com.apes.fn.business.insurance.repository.PolicyInformationItemRepository;
import com.apes.fn.business.insurance.repository.PolicyInformationRepository;
import com.apes.fn.crm.customerExpand.FnCustomerExpandRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.sal.saleOrder.SaleOrder;
import com.apes.scm.sal.saleOrder.SaleOrderRepository;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName CommissionReconciliationService
 * @Author wsj
 * @Date 2021/6/17 17:35
 * @description 业务层
 */
@Service("commissionReconciliationService")
public class CommissionReconciliationService extends DomainService {
    @Autowired
    private CommissionReconciliationRepository reconciliationRepository;
    @Autowired
    private OutboxSubscriberService outboxService;
    @Autowired
    private PolicyInformationRepository policyInformationRepository;
    @Autowired
    private PolicyInformationItemRepository policyInformationItemRepository;
    @Autowired
    private SaleOrderRepository saleOrderRepository;
    @Autowired
    private DeptRepository deptRepository;

    public CommissionReconciliation create(SimpleRequest request) {
        filterInsuranceCommissionItem(request);
        CommissionReconciliation reconciliation = getCommissionReconciliation(request);
        // 因前端必填无效，所以后端判断必填
        checkLack(reconciliation);
        isAllSelectedFalse(reconciliation);
        reconciliation.setCreatorName(((PartyRole)request.getPerson()).getName());
        reconciliation.setState("create");
        filterBySelected(reconciliation);
        computeEveryAmount(reconciliation);
        return reconciliationRepository.saveAndFlush(reconciliation);
    }

    /**
     * 佣金对账单都未勾选
     * @param reconciliation
     */
    private void isAllSelectedFalse(CommissionReconciliation reconciliation){
        List<CommissionReconciliationItem> filterResult = reconciliation.getReconciliationItems().stream().filter(item -> item.isSelected()).collect(Collectors.toList());
        if (!(filterResult.size() > 0)) throw new RuntimeException("请勾选佣金对账明细的保单");
    }

    /**
     * 更新保单标记
     * @param reconciliation
     * @param flag
     */
    private void updatePolicyInformationCommissionFlag(CommissionReconciliation reconciliation,boolean flag) {
        Map<Object, List<Map>> objectListMap = filterAndGroupingByCommissionType(reconciliation,flag);
        deleteSettlementFlag(flag, objectListMap);
    }

    private void deleteSettlementFlag(boolean flag, Map<Object, List<Map>> objectListMap) {
        Iterator<Map.Entry<Object, List<Map>>> iterator = objectListMap.entrySet().iterator();
        //按佣金类型更新
        while (iterator.hasNext()){
            Map.Entry<Object, List<Map>> next = iterator.next();
            String commtype = (String) next.getKey();
            if (commtype==null||"".equals(commtype))continue;
            List<Map> oneTypePolicyNumber = next.getValue();
            List<String> policyNumber = oneTypePolicyNumber.stream().map(jsonObject -> (String)jsonObject.get("policyNumber")).collect(Collectors.toList());
            //如果数据大于一千条则分批更新
            List<String> temp = new ArrayList<>();
            if (!policyNumber.isEmpty()&&policyNumber.size()>999) {
                while (!policyNumber.isEmpty()) {
                    temp.add(policyNumber.remove(0));
                    if (temp.size() == 999) {
                        policyInformationItemRepository.updatePolicyInformationItemSettlement(flag, temp,commtype);
                        temp = new ArrayList<>();
                    }
                }
                policyInformationItemRepository.updatePolicyInformationItemSettlement(flag, temp,commtype);
                temp = new ArrayList<>();
            }else {
                policyInformationItemRepository.updatePolicyInformationItemSettlement(flag, policyNumber,commtype);
            }
        }
    }


    public CommissionReconciliation update(SimpleRequest request) {
        filterInsuranceCommissionItem(request);
        filterBySelectedForTrue(request);
        CommissionReconciliation reconciliation =checkData(request);
        // 因前端必填无效，所以后端判断必填
        checkLack(reconciliation);
        isAllSelectedFalse(reconciliation);
        filterBySelected(reconciliation);
        computeEveryAmount(reconciliation);
        return reconciliationRepository.saveAndFlush(reconciliation);
    }

    /**
     * 前端勾选时会触发生成selectedCondition，用于记录勾选
     * @param request
     */
    private void filterBySelectedForTrue(SimpleRequest request){
        if (!request.getJO().containsKey("selectedCondition")) throw new RuntimeException("请勾选佣金对账明细!");
        JSONArray selectedCondition = request.get("selectedCondition");
        JSONArray reconciliationItems = request.get("reconciliationItems");
        JSONArray reconciliationItemsNew = new JSONArray();
        for (int i = 0; i < reconciliationItems.size(); i++) {
            JSONObject SCJO = (JSONObject) selectedCondition.get(i);
            JSONObject RIJO = (JSONObject) reconciliationItems.get(i);
            RIJO.put("selected",SCJO.get("selected"));
            reconciliationItemsNew.add(RIJO);
        }
        JSONObject jo = request.getJO();
        jo.put("reconciliationItems",reconciliationItemsNew);
        request.setBody(jo.toJSONString());
    }

    private void checkInsuranceCommission(CommissionReconciliation reconciliation){
        List<CommissionReconciliationItem> newItems = reconciliation.getReconciliationItems();
        //检查保险公司佣金明细是否存在于佣金明细 不存在则新增一条
        reconciliation.getInsuranceCommissionItems().stream().forEach(insuranceCommissionItem -> {
            String policyNumber = insuranceCommissionItem.getPolicyNumber();
            List<CommissionReconciliationItem> reconciliationItems = reconciliation.getReconciliationItems().stream().filter(item -> item.getPolicyNumber().equals(policyNumber)).collect(Collectors.toList());
            if (reconciliationItems.size()==0){
                addCommissionReconciliationItem(newItems,insuranceCommissionItem);
            }else {
                reconciliationItems.forEach(commissionReconciliationItem -> commissionReconciliationItem.setSelected(true));
            }
        });
        reconciliation.setReconciliationItems(newItems);
    }

    /**
     * 计算金额
     * @param reconciliation
     */
    private void calculationAmount(CommissionReconciliation reconciliation){
        List<CommissionReconciliationItem> reconciliationItems = reconciliation.getReconciliationItems();
        reconciliation.setCommission(reconciliationItems.stream().mapToDouble(CommissionReconciliationItem::getCommission).sum());
        reconciliation.setInsuranceCommission(reconciliationItems.stream().mapToDouble(CommissionReconciliationItem::getInsuranceCommission).sum());
        reconciliation.setUseInvoiceQuota(reconciliationItems.stream().mapToDouble(CommissionReconciliationItem::getCommission).sum());
        reconciliation.setDifferencePrice(reconciliationItems.stream().mapToDouble(CommissionReconciliationItem::getDifferencePrice).sum());

    }

    /**
     * 过滤佣金明细
     * @param reconciliation
     */
    private void filterBySelected(CommissionReconciliation reconciliation){
        //检查保险公司佣金明细是否存在于佣金明细 不存在则新增一条
        checkInsuranceCommission(reconciliation);
        //更新标记
        updatePolicyInformationCommissionFlag(reconciliation,true);
        updatePolicyInformationCommissionFlag(reconciliation,false);
        //删除未勾选
        List<CommissionReconciliationItem> selected = reconciliation.getReconciliationItems().stream().filter(CommissionReconciliationItem::isSelected).collect(Collectors.toList());
        reconciliation.setReconciliationItems(selected);
        //更新金额
        calculationAmount(reconciliation);
    }

    private Map<Object, List<Map>> filterAndGroupingByCommissionType(CommissionReconciliation reconciliation,Boolean flag){
        List<CommissionReconciliationItem> selected = reconciliation.getReconciliationItems().stream().filter(c -> c.isSelected()==flag).collect(Collectors.toList());
        //初步筛选勾选的商品
        Map<Object, List<Map>> collect = selected.stream()
                .map(c -> MapUtil.mapper("commissionType", c.getCommissionType(), "policyNumber", c.getPolicyNumber()))
                .collect(Collectors.groupingBy(o -> {
                    Object commissionType = ((Map) o).get("commissionType");
                    if (commissionType ==null) commissionType = "";
                    return commissionType;
                }));
        return collect;
    }

    public Page<Map> findSaleOrder(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        List<SaleOrder> allSaleOrder = null;
        addCondition(filters);
        if (!filters.isEmpty()){
            allSaleOrder = saleOrderRepository.findAll(JpaDsl.toCriteria(filters)).stream().filter(saleOrder -> saleOrder.getCommissionFlag().equals("true")).collect(Collectors.toList());
        }else {
            allSaleOrder = saleOrderRepository.findAllByCommissionFlagAndCommissionFlagNotNull("true");
        }
        List<Map> list = allSaleOrder.stream().map(saleOrder -> {
            return MapUtil.mapper("id", saleOrder.getId(),
                    "createDate", saleOrder.getCreateDate()+"",
                    "unsettledAmount", saleOrder.getUnInvoicedAmount(),
                    "dateApprove", saleOrder.getDateApprove()+"",
                    "customer_name", saleOrder.getCustomer()!=null?saleOrder.getCustomer().getName():null,
                    "customer_id", saleOrder.getCustomer()!=null?saleOrder.getCustomer().getId():null
            );
        }).collect(Collectors.toList());
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"));
        PageImpl page = new PageImpl<>(list,pageable, list.size());
        return page;
    }

    private void addCondition(List<Map> filters) {
        Map map = new HashMap();
        map.put("field","commissionFlag");
        map.put("operator","EQ");
        map.put("value","true");
        filters.add(map);
    }

    public CommissionReconciliation approve(SimpleRequest request) {
        CommissionReconciliation reconciliation =checkData(request);
        reconciliation.setApprovePeople(((PartyRole)request.getPerson()).getName());
        reconciliation.setApproveDate(new Date());
        reconciliation.setState("approve");
        reconciliation = reconciliationRepository.saveAndFlush(reconciliation);
        JSONObject data = new JSONObject();
        data.put("id", reconciliation.getId());
        return reconciliation;

    }

    /**
     * 计算每个金额
     * @param reconciliation 佣金对帐单
     */
    private void computeEveryAmount(CommissionReconciliation reconciliation) {
        if (reconciliation.getInsuranceCommissionItems().size() == 0) {
            return;
        }
        reconciliation.getReconciliationItems().forEach(
                item-> {
                    reconciliation.getInsuranceCommissionItems().forEach(
                            towItem -> {
                                if (Objects.equals(item.getPolicyNumber(),towItem.getPolicyNumber())) {
                                    item.setInsuranceCommission(towItem.getCommission());
                                }
                            }
                    );
                    item.setInvoicedAmount(item.getCommission() + item.getAdjustmentAmount());
                    item.setUnInvoicedAmount(Arith.round(item.getInsuranceCommission() -item.getInvoicedAmount(),2));
                    item.setDifferencePrice(Arith.round(item.getCommission() - item.getInsuranceCommission() + item.getAdjustmentAmount(),2));
                }
        );
        double insuranceCommission = reconciliation.getReconciliationItems().stream().mapToDouble(CommissionReconciliationItem::getInsuranceCommission).sum();
        double differencePrice = reconciliation.getReconciliationItems().stream().mapToDouble(CommissionReconciliationItem::getDifferencePrice).sum();
        double usedInvoiceAmount = reconciliation.getReconciliationItems().stream().map(CommissionReconciliationItem::getInvoicedAmount).reduce(Arith::add).orElse(0.0);
        reconciliation.setInsuranceCommission(insuranceCommission);
        reconciliation.setDifferencePrice(differencePrice);
        reconciliation.setUseInvoiceQuota(usedInvoiceAmount);
    }
    private CommissionReconciliation checkData (SimpleRequest request) {
        CommissionReconciliation commissionReconciliation = getCommissionReconciliation(request);
        String id = commissionReconciliation.getId();
        int version = commissionReconciliation.getVersion();
        CommissionReconciliation reconciliation = reconciliationRepository.findOne(id);
        if (Objects.isNull(reconciliation)) {
            throw new RuntimeException("未找到对应佣金对账单,单号: "+ id);
        }
        if (version != reconciliation.getVersion()) {
            throw new RuntimeException("数据发生改变,请刷新重试!!!");
        }
        CommissionReconciliationItem commissionReconciliationItem = commissionReconciliation.getReconciliationItems().stream().filter(reconciliationItem -> {
            String commissionType = reconciliationItem.getCommissionType();
            if (commissionType ==null)return true;
            switch (commissionType){
                case "正常佣金":
                case "追加佣金":
                case "退保佣金":
                case "退保追加佣金":
                    break;
                    default:
                        commissionType=null;
            }
           return commissionType ==null;
        }).findFirst().orElse(null);
        if (commissionReconciliationItem!=null) {
            throw new RuntimeException("存在佣金类型为空的数据或输入错误,保单号为:"+commissionReconciliationItem.getPolicyNumber());
        }
        return commissionReconciliation;
    }

    private CommissionReconciliation getCommissionReconciliation(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONArray retailOrderList = (JSONArray) jo.remove("retailOrderList");
        CommissionReconciliation commissionReconciliation = Tools.map(jo,CommissionReconciliation.class);
        commissionReconciliation.setRetailOrderList(retailOrderList);
        return commissionReconciliation;
    }

    public CommissionReconciliation delete(SimpleRequest request) {
        CommissionReconciliation reconciliation = getCommissionReconciliation(request);
        reconciliation.setState("delete");
        reconciliation.getReconciliationItems().forEach(item -> item.setSelected(true));
        filterBySelected(reconciliation);
        Map<Object, List<Map>> collect = reconciliation.getReconciliationItems().stream()
                .map(c -> MapUtil.mapper("commissionType", c.getCommissionType(), "policyNumber", c.getPolicyNumber()))
                .collect(Collectors.groupingBy(o -> {
                    Object commissionType = ((Map) o).get("commissionType");
                    if (commissionType ==null) commissionType = "";
                    return commissionType;
                }));
        deleteSettlementFlag(false,collect);
        return reconciliationRepository.saveAndFlush(reconciliation);
    }

    /**
     * 查找未对账得有效保单信息
     * @param request
     * @return
     */
    public JSONObject queryEffectivePolicyInformation (SimpleRequest request) {
        JSONObject param = request.getJO();
        JSONObject result = new JSONObject();
        String isInvoice = param.getString("invoice");
        Date startDate = StringUtil.isEmpty(param.getString("startDate")) ? new Date() : param.getDate("startDate");
        Date endDate = StringUtil.isEmpty(param.getString("endDate")) ? new Date() : param.getDate("endDate");
        String supplierId = param.getString("supplier");
        JSONArray commissionType = param.getJSONArray("commissionType");

        JSONArray insuranceType = param.getJSONArray("insuranceType");

        List commissionId = commissionType.stream().map(item -> ((JSONObject) item).getString("id")).collect(Collectors.toList());
        List insuranceId = insuranceType.stream().map(item -> ((JSONObject) item).getString("id")).collect(Collectors.toList());

        CommissionReconciliation reconciliation = reconciliationRepository.findAll(
                JpaDsl.toCriteriaByEq("supplier.id",supplierId)
        ).stream().filter(
                item -> Objects.equals(item.getState(),"create")
        ).findFirst().orElse(null);
        if (Objects.nonNull(reconciliation)) {
            throw new RuntimeException("该保险公司存在新增得佣金对帐单,单号: " + reconciliation.getId());
        }
        if (StringUtil.isEmpty(supplierId) || commissionId.isEmpty()|| insuranceId.isEmpty()) {
            throw new RuntimeException("车险公司/佣金类型/险种类型不能为空!!!");
        }
        List<Map<String, Object>>  policyInformationList =
                reconciliationRepository.queryEffectivePolicyInformation(supplierId,startDate,endDate,commissionId,insuranceId);
        // 保险公司佣金比率、金额≠0
        for (int i = 0; i < policyInformationList.size(); i++) {
            Map<String, Object> commissionReconciliationItem = policyInformationList.get(i);
            Double commissionRatio = (Double) commissionReconciliationItem.get("commissionRatio");
            Double commission = (Double) commissionReconciliationItem.get("commission");
            if (commission == 0 || commissionRatio == 0){
                policyInformationList.remove(i--);
            }
        }
        policyInformationList = policyInformationList.stream().map(item -> {
            Map<String,Object> newItem = new HashMap<>(item);
            if (newItem.containsKey("insuranceType")) newItem.put("insuranceTypeTemp",getInsuranceTypeTemp(item.get("insuranceType").toString()));
            return newItem;
        }).collect(Collectors.toList());
        if (policyInformationList.size() == 0) {
            throw new RuntimeException("该保险公司未存在没有对账得有效保单信息,保险公司编码: " + supplierId );
        }
        PartyRole supplier = SpringManager.getBean(PartyRoleRepository.class).findOne(supplierId);
        double commissionAmount = policyInformationList.stream().mapToDouble(
                item -> (double) item.get("commission")
        ).sum();
        result.put("commissionType", getTypeName(commissionType));
        result.put("insuranceType", getTypeName(insuranceType));
        result.put("invoice", isInvoice.equals("是"));
        result.put("commission", commissionAmount);
        result.put("startDate", DateUtil.dateToStr(startDate));
        result.put("endDate", DateUtil.dateToStr(endDate));
        result.put("supplier", supplier);
        result.put("contract", param.getString("contract"));
        result.put("cooperationType", param.getString("cooperation"));
        result.put("reconciliationItems", policyInformationList);
        return result;
    }

    private Object getInsuranceTypeTemp(String insuranceType){
        Map map = new HashMap<>();
        switch (insuranceType){
            case "商业险":map.put("id","0");map.put("name","商业险");break;
            case "交强险":map.put("id","1");map.put("name","交强险");break;
            case "驾意险":map.put("id","2");map.put("name","驾意险");break;
        }
        return map;
    }

    private String getTypeName(JSONArray type){
        StringBuffer sf = new StringBuffer();
        type.forEach(item ->sf.append(((JSONObject) item).getString("name")+"; "));
        return sf.toString();
    }

    private  String conversionData (String string,String field) {
        Map<String, Object> map = CommissionReconciliationItem.FIELD_COMMENTARY;
        if (!map.containsKey(field)) {
            return "";
        }
        return  JSONObject.parseObject( map.get(field).toString()).getString(string);
    }

    @OutboxSubscriber(id="commissionReconciliation.batchUpdatePolicy", name="回写有效保单信息对账标记")
    private void batchUpdatePolicy(OutboxPayloadWrapper wrapper) {
        JSONObject object = JSON.parseObject(wrapper.getPayload());
        CommissionReconciliation reconciliation = reconciliationRepository.findOne(object.getString("id"));
        if (Objects.isNull(reconciliation)) {
            throw new RuntimeException("未找到佣金对帐单,单号:" + object.getString("id"));
        }
        PolicyInformationItemRepository informationItemRepository = SpringManager.getBean(PolicyInformationItemRepository.class);
        reconciliation.getReconciliationItems().forEach(
                item -> {
                    String commissionType = item.getCommissionType();
                    switch (commissionType){
                        case "正常佣金":
                            commissionType = "PolicyInformationItem.commissionType.A";
                            break;
                        case "追加佣金" :
                            commissionType = "PolicyInformationItem.commissionType.B";
                            break;
                        default:
                            commissionType = "PolicyInformationItem.commissionType.C";

                    }

                    PolicyInformationItem informationItem = informationItemRepository.findAll(
                            JpaDsl.toCriteriaByEq("policyInformation.id", item.getPolicyNumber(), "commissionType.id", commissionType)
                    ).stream().findFirst().orElse(null);
                    if (Objects.nonNull(informationItem)) {
                        informationItem.setSettlement(true);
                        informationItem.setBlendAmount(item.getInvoicedAmount());
                        informationItem.setNotBlendAmount(item.getUnInvoicedAmount());
                        informationItemRepository.saveAndFlush(informationItem);
                    }
                }
        );
    }


    /**
     * 导入保险公司佣金
     *
     */
    public JSONObject importInsuranceCommission(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray field =  request.get("data");
        JSONObject model = request.get("model");
        JSONArray itemArray = model.getJSONArray("insuranceCommissionItems");
        //返回值
        JSONObject exclObject = new JSONObject();
        //field
        getExclObject(importData,field,exclObject);

        return exclObject;
    }

    private void addCommissionReconciliationItem(List<CommissionReconciliationItem> commissionReconciliationItems,InsuranceCommissionItem insuranceCommissionItem){
        CommissionReconciliationItem newItem = new CommissionReconciliationItem();
        String policyNumber = insuranceCommissionItem.getPolicyNumber();
        PolicyInformation policyInformation = policyInformationRepository.findOne(policyNumber);
        if (policyInformation!=null){
            newItem.setCheckAndRatify(policyInformation.getCheckAndRatify());
            newItem.setTransferOwnership(policyInformation.getTransferOwnership());
            newItem.setRenewInsurance(policyInformation.getRenewInsurance());
            newItem.setGrade(policyInformation.getGrade());
            newItem.setEnergy(policyInformation.getEnergy());
        }
        newItem.setPolicyNumber(policyNumber);
        newItem.setCarLicense(insuranceCommissionItem.getCarLicense());
        newItem.setStartDate(insuranceCommissionItem.getStartDate());
        newItem.setNetPremium(insuranceCommissionItem.getNetPremium());
        newItem.setCommission(0);
        newItem.setCommissionRatio(insuranceCommissionItem.getCommissionRatio());
        newItem.setInsuranceAmount(0.0);
        newItem.setSelected(true);
        newItem.setDept(insuranceCommissionItem.getDept());
        newItem.setInsuranceType(insuranceCommissionItem.getInsuranceType());
        newItem.setCity(insuranceCommissionItem.getCity());
        newItem.setProvince(insuranceCommissionItem.getProvince());
        commissionReconciliationItems.add(newItem);
    }

    //导入佣金对账明细
    private JSONObject importReconciliationItems(SimpleRequest request){
//Excel信息
        JSONObject importData = request.get("importData");
        JSONArray field =  request.get("data");
        JSONObject model = request.get("model");
        Boolean lineNumber = false ;
        JSONArray itemArray = model.getJSONArray("reconciliationItems");
        //返回值
        JSONObject exclObject = new JSONObject();
        getExclObject(importData, field, exclObject);
        return exclObject;
    }

    /**
     *  传入导入数据 返回与页签字段相匹配顺序的Map<fileName,List<List>>
     *
     * @param importData 导入数据
     * @param field 页签字段
     * @param exclObject 返回结果集
     */
    private void getExclObject(JSONObject importData, JSONArray field, JSONObject exclObject) {
        Iterator<Map.Entry<String, Object>> iterator = importData.entrySet().iterator();
        if (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            //当前页数据
            JSONArray importDataList = (JSONArray) next.getValue();
            //返回值页签内容
            JSONArray resultPage = new JSONArray();
            //获取导入字段索引
            Map<String, Integer> importFiledIndex = getIndex(importDataList);
            //获取当前页签字段
            List<String> returnFiled = field.stream().map(o -> ((JSONObject) o).getString("name")).collect(Collectors.toList());
            //首行添加标题
            resultPage.add(returnFiled);
            importDataList.forEach(excl -> {
                //当前行
                JSONArray line = (JSONArray) excl;
                //按字段取值
                //返回值行内容
                JSONArray resultLine = new JSONArray();
                returnFiled.forEach(s -> {
                    //获取当前字段索引
                    Integer index = importFiledIndex.get(s);
                    if (index==null||line.size()-1<index) {
                        resultLine.add("");
                    }else {
                        wrapperResultLine(resultLine,line,index,s);
                    }
                });
                long count = resultLine.stream().filter(item -> !item.toString().replace(" ", "").equals("")).count();
                if (count != 0) resultPage.add(resultLine);
            });
            exclObject.put(next.getKey(),resultPage);
        }
    }

    /**
     * 格式化导入数据的值
     * @param s 导入的列名
     * @param o 当前列数据
     * @return
     */
    private Object formatValue(String s, Object o)  {
        try {
            if (s.contains("时间")||s.contains("日期")){
                if (!o.equals("")){
                    if (o instanceof Integer){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date parse = sdf.parse("1899-12-30");
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(parse);
                        calendar.add(Calendar.DATE,(Integer) o);
                        Date date = calendar.getTime();
                        o = sdf.format(date);

                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return o;
    }

    private Map<String, Integer> getIndex(JSONArray importDataList) {
        Map<String,Integer> index = new HashMap();
        JSONArray importLineName = (JSONArray) importDataList.remove(0);
        for (int i = 0; i < importLineName.size(); i++) {
            index.put(importLineName.getString(i),i);
        }
        return index;
    }

    private void checkLack(CommissionReconciliation reconciliation){
        reconciliation.getReconciliationItems().stream().forEach(commissionReconciliationItem -> {
            if (commissionReconciliationItem.getInsuranceType() == null) throw new RuntimeException("佣金对账明细的险种类别必填！保单号["+commissionReconciliationItem.getPolicyNumber()+"]");
        });
    }

    private void wrapperResultLine(JSONArray resultLine,JSONArray line,Integer index,String s){
        Object o = line.get(index);
        if (o==null)o="";
        String lineContent = o.toString().trim();
        if(!s.equals("门店")){
            resultLine.add(formatValue(s, lineContent));
        }else{
            List<Dept> depts = deptRepository.findByName(lineContent);
            if (!StringUtil.isEmpty(lineContent)) {
                Dept deptData = deptRepository.findOne(lineContent);
                if (!Objects.isNull(deptData)) depts.add(deptData);
            }
            Dept dept = new Dept();
            if (depts.size() > 1){
                dept = depts.stream().filter(dept1 -> dept1.getOrigin() != null).collect(Collectors.toList()).get(0);
            }else{
                dept = depts.size() > 0 ?  depts.get(0) : null;
            }
            if (dept == null) throw new RuntimeException("没有找到"+lineContent+"的门店");
            resultLine.add(dept);
        }
    }

    /**
     * 保险公司佣金对账明细导入时会导入空字符串，需要排除
     * @param request
     */
    private void filterInsuranceCommissionItem(SimpleRequest request){
        JSONObject jo = request.getJO();
        if (!jo.containsKey("insuranceCommissionItems")) return;
        // 将保险公司明细的部门为空字符串替换为null
        JSONArray insuranceCommissionItems = jo.getJSONArray("insuranceCommissionItems");
        List newData = insuranceCommissionItems.stream().map(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Object dept = jsonObject.get("dept");
            if (dept == null) return item;
            if (dept.toString().replace(" ", "").equals("")){
                jsonObject.put("dept",null);
            }
            return jsonObject;
        }).collect(Collectors.toList());
        jo.put("insuranceCommissionItems",newData);
        request.setBody(jo.toJSONString());
    }
}
